const { OBSERVERS } = require('./const');
const { setProp } = require('./helper');

class EventEmitter {
    constructor() {
        setProp(this, OBSERVERS, {});
    }

    on(type, fn) {
        if (!this[OBSERVERS][type]) {
            this[OBSERVERS][type] = [];
        }
        if (this[OBSERVERS][type].indexOf(fn) === -1) {
            this[OBSERVERS][type].push(fn);
        }
        return this;
    }

    emit(type, data) {
        let targets = this[OBSERVERS][type] || [];
        return targets.reduce((a, observer) => {
            return a.then(() => {
                return new Promise(resolve => {
                    Promise.resolve().then(() => observer(data)).then(a => resolve(a), a => {
                        console.error(a);
                        resolve();
                    });
                });
            });
        }, Promise.resolve());
    }
}

module.exports = EventEmitter;